package com.jxwifi.cloud.quickcleanserver;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.basicactivity.BasicActivity;
import com.bumptech.glide.Glide;
import com.idroid.utils.MToast;
import com.idroid.utils.NoDoubleClickListener;
import com.jxwifi.cloud.quickcleanserver.adapter.MyFragmentPagerAdapter;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.CleaningApplication;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.login.LoginActivity;
import com.jxwifi.cloud.quickcleanserver.main.MyFragment;
import com.jxwifi.cloud.quickcleanserver.main.OrderFormFragment;
import com.jxwifi.cloud.quickcleanserver.main.WorkbenchFragment;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.upgrade.UpgradeNotice;
import com.jxwifi.cloud.quickcleanserver.utils.AlterLocation;
import com.jxwifi.cloud.quickcleanserver.utils.Constants;
import com.jxwifi.cloud.quickcleanserver.utils.KAlertDialog;
import com.jxwifi.cloud.quickcleanserver.utils.LocationGaoDe;
import com.jxwifi.cloud.quickcleanserver.utils.NoScrollViewPager;
import com.jxwifi.cloud.quickcleanserver.utils.NotifySetting;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * Created by Administrator on 2019/5/11.
 */

public class MainActivity extends CleanBasicActivity {


    @Bind(R.id.rb_order_form)
    RadioButton mRbOrderForm;//找订单
    @Bind(R.id.rb_workbench)
    RadioButton mRbWorkbench;//工作台
    @Bind(R.id.rb_me)
    RadioButton mRbMe;//我的
    private NoScrollViewPager mVpMain;//初始化的时候如果下面2个空间用ButterKnife注解的话会出现空指针，
    private RadioGroup mRgBottom;

    private OrderFormFragment mOrderFormFragment;//找订单fg
    private WorkbenchFragment mRbWorkbenchFragment;//工作台fg
    private MyFragment mMyFragment;//我的fg

    private int loginCount = 0;

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        openEventBus();
        new LocationGaoDe().init(getApplicationContext());
        LocationGaoDe.startLocation();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                UpgradeNotice.UpgradeData(mBaseContext,TAG, 1,MainActivity.this);//升级通知
            }
        }, 500);
        refreshlocation();
        initView();
        /*Intent i = new Intent(mBaseContext, CycleService.class);
        startService(i);*/
        NotifySetting.checkNotifySetting(mBaseContext);
        IndexMain(Integer.valueOf(getIntent().getStringExtra("mainindex")));

        //当系统小于6.0的时候另做处理
        if (isPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION,
                Constants.QUEST_CODE_LOCTION)) {
        }
        //Log.i(TAG, "province = " + LocationGaoDe.getProvince() + " city = " + LocationGaoDe.getCity() + " area = " + LocationGaoDe.getDistrict());
    }

    public void initView(){
        mVpMain=findViewById(R.id.vp_main);
        mRgBottom=findViewById(R.id.rg_bottom);
        List<Fragment> fragment = new ArrayList<Fragment>();
        fragment.add(mOrderFormFragment= new OrderFormFragment());
        fragment.add(mRbWorkbenchFragment= new WorkbenchFragment());
        fragment.add(mMyFragment= new MyFragment());
        MyFragmentPagerAdapter maintenanceAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragment);
        mVpMain.setOffscreenPageLimit(fragment.size());//缓存Fragment数量，让他不再重新创建
        mVpMain.setAdapter(maintenanceAdapter);
        initListener();
    }

    private void initListener() {
        mRgBottom.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId==R.id.rb_order_form){
                    mVpMain.setCurrentItem(0);
                }else if(checkedId==R.id.rb_workbench){
                    if (!AccountMgr.isLogin(mBaseContext)){
                        if (mVpMain.getCurrentItem()==0){
                            mRbOrderForm.setChecked(true);
                        }
                        if (mVpMain.getCurrentItem()==2){
                            mRbMe.setChecked(true);
                        }
                        startActivity(new Intent(mBaseContext, LoginActivity.class));
                    }else{
                        if (isPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION,
                                Constants.QUEST_CODE_LOCTION)) {
                            mVpMain.setCurrentItem(1);
                        }else{
                            if (mVpMain.getCurrentItem()==0){
                                mRbOrderForm.setChecked(true);
                            }
                            if (mVpMain.getCurrentItem()==2){
                                mRbMe.setChecked(true);
                            }
                            Permiss();
                        }
                    }
                }else if(checkedId==R.id.rb_me){
                    if (!AccountMgr.isLogin(mBaseContext)){
                        if (mVpMain.getCurrentItem()==0){
                            mRbOrderForm.setChecked(true);
                        }
                        if (mVpMain.getCurrentItem()==1){
                            mRbWorkbench.setChecked(true);
                        }
                        startActivity(new Intent(mBaseContext, LoginActivity.class));
                    }else{
                        mVpMain.setCurrentItem(2);
                    }
                }
            }
        });
    }

    public void IndexMain(int index){
        if (index == 0) {
            mVpMain.setCurrentItem(0);
            mRbOrderForm.setChecked(true);
        }else if (index==1){
            if (!AccountMgr.isLogin(mBaseContext)){
                if (mVpMain.getCurrentItem()==0){
                    mRbOrderForm.setChecked(true);
                }
                if (mVpMain.getCurrentItem()==2){
                    mRbMe.setChecked(true);
                }
                startActivity(new Intent(mBaseContext, LoginActivity.class));
            }else{
                if (isPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Constants.QUEST_CODE_LOCTION)) {
                    mVpMain.setCurrentItem(1);
                    mRbWorkbench.setChecked(true);
                }else{
                    if (mVpMain.getCurrentItem()==0){
                        mRbOrderForm.setChecked(true);
                    }
                    if (mVpMain.getCurrentItem()==2){
                        mRbMe.setChecked(true);
                    }
                    Permiss();
                }
            }
        }else if (index==2){
            if (!AccountMgr.isLogin(mBaseContext)){
                if (mVpMain.getCurrentItem()==0){
                    mRbOrderForm.setChecked(true);
                }
                if (mVpMain.getCurrentItem()==1){
                    mRbWorkbench.setChecked(true);
                }
                startActivity(new Intent(mBaseContext, LoginActivity.class));
            }else{
                mVpMain.setCurrentItem(2);
                mRbMe.setChecked(true);
            }
        }

    }

    @Override
    public void onBackPressed() {
        /*long secondTime = System.currentTimeMillis();
        if (secondTime - mClickFirstTime > 2000) {
            Toast.makeText(mBaseContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mClickFirstTime = secondTime;
            return;
        } else {
            Glide.get(mBaseContext).clearMemory();
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(EXITAPP));
            System.gc();
        }*/

        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.w("oushuhua", " MainActivity onResume" );
        if (CleaningApplication.JUMP_TYPE!=100){
            if (CleaningApplication.JUMP_TYPE == 50){
                IndexMain(1);
            }else{
                mRbOrderForm.setChecked(true);
                mVpMain.setCurrentItem(CleaningApplication.JUMP_TYPE);
            }
            CleaningApplication.JUMP_TYPE = 100;
        }
    }

    public void Permiss(){
        if (Build.VERSION.SDK_INT <= 22) {
            final KAlertDialog dialog = new KAlertDialog(mBaseContext, "定位权限已关闭\", \"定位权限已被禁止，请在设置中开启");
            dialog.setRightTxt("去查看", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //前往应用详情界面
                    try {
                        Uri packUri = Uri.parse("package:" + mBaseContext.getPackageName());
                        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packUri);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } catch (Exception e) {
                        MToast.shortToast(mBaseContext, "跳转失败");
                    }
                    dialog.dismiss();
                }
            });
            dialog.setLeftTxt("取消", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

    protected boolean isPermissionGranted(String permissionName, int questCode) {
        //6.0以下系统，取消请求权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        //判断是否需要请求允许权限，否则请求用户授权
        int hasPermision = checkSelfPermission(permissionName);
        if (hasPermision != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{permissionName}, questCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length == 0) {
            return;
        }
        switch (requestCode) {
            case Constants.QUEST_CODE_LOCTION:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    AlterLocation.popAlterDialog(mBaseContext, "定位服务已关闭", "请到设置->定位服务中开启[快洁帮专员]定位服务，以便能够准确获得您的位置");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
                break;
        }
    }

    public void refreshlocation() {
        if (LocationGaoDe.getLongitude()==0.0){
            return;
        }
        Log.w("oushuhua","REAL_LOCATION");
        Params params = new Params();
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("lat", LocationGaoDe.getLatitude());
        AuzHttp.get(UrlPool.UPDATE_REAL_LOCATION, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code,String data) {

            }

            @Override
            public void onFailure(int errorCode, String msg) {

            }
        }, "");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            conLogout();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void conLogout(){
        final KAlertDialog dialogshow=new KAlertDialog(mBaseContext,"您是否要退出？");
        dialogshow.setTitleText("提示");
        dialogshow.setRightTxt("确定", new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                dialogshow.dismiss();
                Glide.get(mBaseContext).clearMemory();
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(EXITAPP));
                System.gc();
            }
        });
        dialogshow.show();


    }


}

